const fs = require('fs')

const { PICTURE_PATH } = require('../constants/file-path')
const pictureType = require('../constants/picture-type')

const fileService = require('../services/file.service')
const momentService = require('../services/moment.service')

class MomentController {
	async create(ctx, next) {
		// 获取数据(userId, content)
		const userId = ctx.user.id
		const content = ctx.request.body.content

		console.log(userId, content)

		// 将数据插入数据库中
		const result = await momentService.create(userId, content)
		ctx.body = result
	}

	async detail(ctx, next) {
		const momentId = ctx.request.params.momentId
		console.log('momentId: ', momentId)
		const result = await momentService.getMomentById(momentId)
		ctx.body = result[0]
	}

	async list(ctx, next) {
		const { offset, size } = ctx.request.query
		const result = await momentService.getMomentList(offset, size)
		ctx.body = result
	}

	async update(ctx, next) {
		const { momentId } = ctx.request.params
		const { content } = ctx.request.body

		const result = await momentService.update(momentId, content)
		ctx.body = result

		// ctx.body = '修改动态' + momentId + content + id
	}

	async remove(ctx, next) {
		const { momentId } = ctx.request.params
		const result = await momentService.remove(momentId)
		ctx.body = result
	}

	async addLabels(ctx, next) {
		const { momentId } = ctx.request.params
		const { labels } = ctx
		for (let label of labels) {
			// 判断标签是否与动态有关联
			const isExisted = await momentService.hasLabels(momentId, label.id)
			if (!isExisted) {
				momentService.addLabels(momentId, label.id)
			}
		}

		ctx.body = '给动态添加标签成功~'
	}

	async pictureInfo(ctx, next) {
		let { filename } = ctx.request.params
		const [picture] = await fileService.getPictureByFileName(filename)
		const { type } = ctx.request.query
		// console.log('picture: ---', picture, type, filename)
  
		if (Object.values(pictureType).some((item) => item === type)) {
			filename = filename + '-' + type
		}
    
		// console.log('picture_full_path: ', `${PICTURE_PATH}/${filename}`)

		ctx.response.set('content-type', picture.mimetype)
		ctx.body = fs.createReadStream(`${PICTURE_PATH}/${filename}`)
	}
}

module.exports = new MomentController()
